<template>
	<view class="xl-swiper" :style="{ backgroundColor: bgColor, height: $xl.calcUnit(height, 'rpx')}">
		<view v-if="loading" class="xl-swiper__loading">
			<xl-loading type="halfCircle"></xl-loading>
		</view>
		<swiper
			v-else
			class="xl-swiper__wrapper"
			:style="{height: $xl.calcUnit(height, 'rpx'), borderRadius: $xl.calcUnit(radius)}"
			@change="change"
			:circular="circular"
			:interval="interval"
			:duration="duration"
			:autoplay="autoplay"
			:current="current"
			:currentItemId="currentItemId"
			:previousMargin="$xl.calcUnit(previousMargin)"
			:nextMargin="$xl.calcUnit(nextMargin)"
			:acceleration="acceleration"
			:displayMultipleItems="displayMultipleItems"
			:easingFunction="easingFunction"
		>
			<swiper-item v-for="(item, index) in list" :key="index" class="xl-swiper__wrapper__item">
				<view class="xl-swiper__wrapper__item__wrapper" :style="[itemStyle(index)]">
					<!-- 在nvue中，image图片的宽度默认为屏幕宽度，需要通过flex:1撑开，另外必须设置高度才能显示图片 -->
					<xl-image
						class="xl-swiper__wrapper__item__wrapper__image"
						v-if="getItemType(item) === 'image'"
						:src="getSource(item)"
						:mode="imgMode"
						@click="clickHandler(item, index)"
						:height="$xl.calcUnit(height, 'rpx')"
						:borderRadius="$xl.calcUnit(radius)"
					></xl-image>
					<xl-icon v-if="item.sourceType == 'video'" style="position: absolute;top: 50%;transform: translateY(-50%);bottom: 0;left: 0;right: 0;margin: auto;width: 45px;" name="xl-play" color="rgba(0,0,0,0.2)" size="45" @tap="clickHandler(item, index)"></xl-icon>
					<video
						class="xl-swiper__wrapper__item__wrapper__video"
						v-if="getItemType(item) === 'video'"
						:id="`video-${index}`"
						:enable-progress-gesture="false"
						:src="getSource(item)"
						:poster="getPoster(item)"
						:title="showTitle && $xl.validate.object(item) && item.title ? item.title : ''"
						:style="{
							height: $xl.calcUnit(height, 'rpx')
						}"
						controls
						@tap="clickHandler(item, index)"
					></video>
					<text
						v-if="showTitle && $xl.validate.object(item) && item.title && $xl.validate.image(getSource(item))"
						class="xl-swiper__wrapper__item__wrapper__title u-line-1"
					>{{ item.title }}</text>
				</view>
			</swiper-item>
		</swiper>
		<view class="xl-swiper__indicator" :style="[$xl.convertStyle(indicatorStyle)]">
			<slot name="indicator">
				<view v-if="!loading && indicator && !showTitle" class="xl-swiper-indicator">
					<view
						class="xl-swiper-indicator__wrapper"
						v-if="indicatorMode === 'line'"
						:class="[`xl-swiper-indicator__wrapper--${indicatorMode}`]"
						:style="{
							width: $xl.calcUnit(lineWidth * list.length),
							backgroundColor: indicatorInactiveColor
						}"
					>
						<view
							class="xl-swiper-indicator__wrapper--line__bar"
							:style="[lineStyle]"
						></view>
					</view>
					<view
						class="xl-swiper-indicator__wrapper"
						v-if="indicatorMode === 'dot'"
					>
						<view
							class="xl-swiper-indicator__wrapper__dot"
							v-for="(item, index) in list.length"
							:key="index"
							:class="[index === currentIndex && 'xl-swiper-indicator__wrapper__dot--active']"
							:style="[dotStyle(index)]"
						>
						</view>
					</view>
					<view v-if="indicatorMode === 'num'" class="xl-swiper-indicator__num">
						<view class="xl-swiper-indicator__num_left flex-1">{{ currentIndex + 1 }}</view> 
						<view class="xl-swiper-indicator__num_middle">/</view>
						<view class="xl-swiper-indicator__num_right flex-1"> {{ list.length }}</view>
					</view>
				</view>
			</slot>
		</view>
	</view>
</template>

<script setup>
	
	import propsData from './props.js'
	const props = defineProps(propsData)
	
	import { ref, watch, computed, useSlots } from 'vue'
	const emits = defineEmits(['change', 'click'])
	
	const currentIndex = ref(0)
	watch(() => props.current, ( newValue, oldValue ) => {
		if(newValue === oldValue) return;
		currentIndex.value = newValue;
	})
	
	let itemStyle = computed(()=>{
		return index => {
			const style = {}
			// #ifndef APP-NVUE || MP-TOUTIAO
			// 左右流出空间的写法不支持nvue和头条
			// 只有配置了此二值，才加上对应的圆角，以及缩放
			if (props.nextMargin && props.previousMargin) {
				style.borderRadius = uni.$xl.calcUnit(props.radius)
				if (index !== currentIndex.value && (props.previousMargin != 0 || props.nextMargin != 0)) style.transform = 'scale('+props.inactiveScale+')'
			}
			// #endif
			return style
		}
	})
	
	// 指示器为线型的样式
	const lineWidth = ref(22)
	let lineStyle = computed(()=>{
		let style = {}
		style.width = uni.$xl.calcUnit(lineWidth.value)
		style.transform = `translateX(${ uni.$xl.calcUnit(currentIndex.value * lineWidth.value) })`
		style.backgroundColor = props.indicatorActiveColor
		return style
	})
	// 指示器为点型的样式
	let dotStyle = computed(()=>{
		return index => {
			let style = {}
			style.backgroundColor = index === currentIndex.value ? props.indicatorActiveColor : props.indicatorInactiveColor
			return style
		}
	})
	
	
	function getItemType(item) {
		if (typeof item === 'string') return uni.$xl.validate.video(getSource(item)) ? 'video' : 'image'
		if (typeof item === 'object' && props.urlName) {
			if (!item.type) return uni.$xl.validate.video(getSource(item)) ? 'video' : 'image'
			if (item.type === 'image') return 'image'
			if (item.type === 'video') return 'video'
			return 'image'
		}
	}
	
	// 获取目标路径，可能数组中为字符串，对象的形式，额外可指定对象的目标属性名urlName
	function getSource(item) {
		if (typeof item === 'string') return item
		if (typeof item === 'object' && props.urlName) return item[props.urlName]
		else uni.$xl.error('请按格式传递列表参数')
		return ''
	}
	
	// 轮播切换事件  轮播图切换时触发change (自动或者手动切换)	index：切换到了第几张图片，从0开始
	function change(e) {
		// 当前的激活索引
		const {
			current
		} = e.detail
		pauseVideo(currentIndex.value)
		currentIndex.value = current
		emits('change', e.detail)
	}
	
	// 切换轮播时，暂停视频播放
	function pauseVideo(index) {
		const lastItem = getSource(props.list[index])
		if (uni.$xl.validate.video(lastItem)) {
			// 当视频隐藏时，暂停播放
			const video = uni.createVideoContext(`video-${index}`, this)
			video.pause()
		}
	}
	
	// 当一个轮播item为视频时，获取它的视频海报
	function getPoster(item) {
		return typeof item === 'object' && item.poster ? item.poster : ''
	}
	
	// 点击轮播图时触发	index：点击了第几张图片，从0开始
	function clickHandler(item, index) {
		if(props.router && uni.$xl.validate.object(item) && item.path && getItemType(item) == 'image'){
			uni.$xl.router.push(item.path)
		}
		emits('click', index)
	}
</script>

<style lang="scss" scoped>
	.xl-swiper {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		justify-content: center;
		align-items: center;
		position: relative;
		&__wrapper {
			flex: 1;
			&__item {
				flex: 1;

				&__wrapper {
					/* #ifndef APP-NVUE */
					display: flex;
					/* #endif */
					flex-direction: row;
					position: relative;
					overflow: hidden;
					transition: transform 0.3s;
					flex: 1;

					&__image {
						flex: 1;
					}

					&__video {
						flex: 1;
					}

					&__title {
						position: absolute;
						background-color: rgba(0, 0, 0, 0.3);
						bottom: 0;
						left: 0;
						right: 0;
						font-size: 28rpx;
						padding: 12rpx 24rpx;
						color: #FFFFFF;
						flex: 1;
					}
				}
			}
		}

		&__indicator {
			position: absolute;
			bottom: 10px;
			z-index: 50;
		}
	}
	.xl-swiper-indicator__num {
		display: flex;
		background-color: rgba(0, 0, 0, .2);
		color: #fff;
		padding: 8rpx 20rpx;
		border-radius: 5000px;
		font-size: 24rpx;
		&_middle {
			margin: 0 8rpx;
		}
	}
	.xl-swiper-indicator {
		&__wrapper {
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			flex-direction: row;
			&--line {
				border-radius: 100px;
				height: 4px;

				&__bar {
					width: 22px;
					height: 4px;
					border-radius: 100px;
					background-color: #FFFFFF;
					transition: transform 0.3s;
				}
			}

			&__dot {
				width: 5px;
				height: 5px;
				border-radius: 100px;
				margin: 0 4px;

				&--active {
					width: 12px;
				}
			}

		}
	}
</style>
